package be.colwri.client;

import java.util.Vector;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Colwri implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	//private final GreetingServiceAsync greetingService = GWT
	//S		.create(GreetingService.class);
	private final ColwriServiceAsync colwriService = GWT.create(ColwriService.class);
	
	private Vector<Command> commandvec = new Vector<Command>();


	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button sendButton = new Button("Send");
		final TextArea nameField = new TextArea();
		nameField.setVisibleLines(10);
		nameField.setCharacterWidth(40);
	
		nameField.setText("GWT User");
		nameField.setText("");

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler, KeyPressHandler, ChangeListener {
			private String oldstring = ""; 
			private String newstring = "";
			
			private int compareString(String compare)
			{int i = 0;
			while ((i<Math.min(compare.length(), oldstring.length())) && (compare.substring(0,i).equals(oldstring.substring(0,i)) )) {
				i++;
			}
			if (i < Math.min(compare.length(), oldstring.length())) {
				   i--;
			   }
			i--;
			/*
				try {
				boolean b = false;
				System.out.println(compare + oldstring);
			   while ((b == false) && (i<Math.min(compare.length(), oldstring.length()))) {
				  
				   i++; System.out.println(i);
				   if ((!compare.substring(0, i).equals(oldstring.substring(0, i))) || (i == Math.min(compare.length(), oldstring.length()))) {
					   b = true; 
					   if (i <= Math.min(compare.length(), oldstring.length())) {
						   i--;
					   }
				   }
			   }
			   */
			System.out.println(i);
			   return i;
			  /* }
				catch (Exception e) {
					 System.out.println("Result 0");
				 return 0;	
				
				}*/
			   
			}
			
			
			
			
			
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					//sendNameToServer();
				}
				else {
					oldstring = nameField.getText();
				}
			}
			
			private boolean isNotChanging(char ch)  {
				if ((ch == KeyCodes.KEY_DOWN) || (ch == KeyCodes.KEY_UP) || (ch == KeyCodes.KEY_LEFT) 
						|| (ch == KeyCodes.KEY_RIGHT) || (ch == KeyCodes.KEY_ALT) || (ch == KeyCodes.KEY_CTRL)
						|| (ch == KeyCodes.KEY_END) || (ch == KeyCodes.KEY_ESCAPE) || (ch == KeyCodes.KEY_HOME)
						|| (ch == KeyCodes.KEY_PAGEDOWN) || (ch == KeyCodes.KEY_PAGEUP) || (ch == KeyCodes.KEY_SHIFT)) {
					return true;
				}
				else {
					return false;
				}
			}
			
			private boolean isDeletionChar (char ch) {
				if ((ch == KeyCodes.KEY_DELETE) || (ch == KeyCodes.KEY_BACKSPACE)) {
					return true;
				}
				else return false;
			}
			
			
			
			public void onKeyPress(KeyPressEvent event) {
				System.out.println("KeyPressed:" + event.getCharCode() + " old:" + oldstring + " nieuw:" +nameField.getText() + "Cursorpos: " + nameField.getCursorPos());
				if (!nameField.getSelectedText().equals("")) {
					if (!isNotChanging(event.getCharCode()) ) {
						RemoveCommand rc2 = new RemoveCommand(nameField.getCursorPos(), nameField.getSelectionLength());
						commandvec.add(rc2);
					}
					System.out.println(nameField.getSelectedText());
				}
		/*		if (event.getCharCode() != KeyCodes.KEY_BACKSPACE) {
					if (nameField.getCursorPos() > 0) {
						if (nameField.getCursorPos() < oldstring.length()) {
					      newstring = oldstring.substring(0, nameField.getCursorPos()) + event.getCharCode() + oldstring.substring(nameField.getCursorPos());
					      
						}
						else {
							newstring = oldstring + event.getCharCode();
						}
					}
					else {
						newstring = event.getCharCode() + oldstring;  
					}
				}
				System.out.println(newstring);*/
			
				
				/*****  Now writing something with Keycodes ************/
				if (!isNotChanging(event.getCharCode()) && (!isDeletionChar(event.getCharCode()))) {
					char[] ck = new char[1];
		            ck[0] = event.getCharCode();
					AddCommand c = new AddCommand(new String(ck), nameField.getCursorPos());
					commandvec.add(c);
				}
				else {
					
					
					RemoveCommand rc = new RemoveCommand (nameField.getCursorPos(), 1);
					commandvec.add(rc);
					System.out.println("Removed something" + nameField.getCursorPos());
				}
				/*
				if (!oldstring.equals(nameField.getText())) {
					if (oldstring.length() < nameField.getText().length()) {
						
						//int it = compareString(nameField.getText());
				
	//					if (it <= nameField.getText().length()) {
	//						char[] ck = new char[1];
							
	//						ck[0] = new Character((char) event.getNativeKeyCode());
		//					AddCommand c = new AddCommand(new String(ck), it);
		//					commandvec.add(c);
		//					System.out.println("Key Pressed");
		//					oldstring = nameField.getText();
		//				}
						char[] ck = new char[1];
						
						ck[0] = new Character(event.getCharCode());
						AddCommand rc = new AddCommand (new String(ck), nameField.getCursorPos() - 2);
						commandvec.add(rc);
						System.out.println("Added something" + new String (ck) + (nameField.getCursorPos() - 2));
					
					}
					else {
						RemoveCommand rc = new RemoveCommand (nameField.getCursorPos(), 1);
						commandvec.add(rc);
						System.out.println("Removed something" + nameField.getCursorPos());
						
					}
				}
				oldstring = newstring;
				*/ 
			}
			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			int lastind = 0;
			private void sendNameToServer() {
				
				
				sendButton.setEnabled(false);
				String textToServer = nameField.getText();
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
			/*	greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});*/
				//commandar[0] = com;
				colwriService.getString(commandvec, lastind, new AsyncCallback<CPResult>() {
				  public void onFailure(Throwable caught) {
					  dialogBox
						.setText("Remote Procedure Call - Failure");
				serverResponseLabel
						.addStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(SERVER_ERROR);
				dialogBox.center();
				closeButton.setFocus(true);
				  }
				  public void onSuccess(CPResult res) {
					  dialogBox.setText("Remote Procedure Call2" + res.getResult());
					  serverResponseLabel
						.removeStyleName("serverResponseLabelError");
				serverResponseLabel.setHTML(res.getResult());
					  dialogBox.center();
					  lastind = res.getLastindex();
					  nameField.setText(res.getResult());
					  oldstring = nameField.getText(); /**oldstring verzetten **/
					  commandvec.clear();
					  closeButton.setFocus(true);
				  }
				});
			}





			@Override
			public void onChange(Widget sender) {
				// TODO Auto-generated method stub
				System.out.println(nameField.getText());
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
		nameField.addKeyPressHandler(handler);
	
	}
}
